package com.harassment.interception.ui.activities.main;

import android.annotation.SuppressLint;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.harassment.interception.R;
import com.harassment.interception.interception.telephone.TelephoneRecord;

import java.io.File;
import java.util.Arrays;
import java.util.List;

import io.reactivex.Completable;
import io.reactivex.CompletableEmitter;
import io.reactivex.CompletableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.schedulers.Schedulers;

public class RecordListAdapter extends RecyclerView.Adapter<RecordListAdapter.RecordListViewHolder> {
    private List<String> mRecordFileLists;

    @SuppressLint("CheckResult")
    public RecordListAdapter() {
        Completable.create(new CompletableOnSubscribe() {
            @Override
            public void subscribe(CompletableEmitter emitter) throws Exception {
                File file = TelephoneRecord.getPath();
                file.list();
                mRecordFileLists = Arrays.asList(file.list());
                emitter.onComplete();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action() {
                    @Override
                    public void run() throws Exception {
                        RecordListAdapter.this.notifyDataSetChanged();
                    }
                });
    }

    @NonNull
    @Override
    public RecordListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_record_item, parent, false);
        return new RecordListViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecordListViewHolder holder, int position) {
        holder.fileName.setText(mRecordFileLists.get(position));
    }

    @Override
    public int getItemCount() {
        return (mRecordFileLists == null) ? 0 : mRecordFileLists.size();
    }

    static class RecordListViewHolder extends RecyclerView.ViewHolder {
        TextView fileName;

        public RecordListViewHolder(View itemView) {
            super(itemView);
            fileName = itemView.findViewById(R.id.file_name);
        }
    }

}
